// vuex的构造函数刚开始使用了断言函数
; (function () {
    return
    let assert = function (condition, msg) {
        if (!condition) throw new Error(`[vuex] ${msg}`)
    }
    let Vue = {}
    // 其中Vue是看是否已经install了 
    assert(Vue, `must call Vue.use(Vuex) before creating a store instance.`)
    assert(typeof Promise !== 'undefined', `vuex requires a Promise polyfill in this browser.`)

    console.log("执行到这里说明上面俩个通过了")

})();

// 刚开始暴露的install
; (function () {
    //return
    // 这段代码还不是很理解.
    let applyMixin = function (Vue) {
        const version = Number(Vue.version.split('.')[0])

        if (version >= 2) {
            const usesInit = Vue.config._lifecycleHooks.indexOf('init') > -1
            Vue.mixin(usesInit ? { init: vuexInit } : { beforeCreate: vuexInit })
        } else {
            // override init and inject vuex init procedure
            // for 1.x backwards compatibility.
            const _init = Vue.prototype._init
            Vue.prototype._init = function (options = {}) {
                options.init = options.init
                    ? [vuexInit].concat(options.init)
                    : vuexInit
                _init.call(this, options)
            }
        }

        /**
         * Vuex init hook, injected into each instances init hooks list.
         */

        function vuexInit() {
            const options = this.$options
            // store injection
            if (options.store) {
                this.$store = options.store
            } else if (options.parent && options.parent.$store) {
                this.$store = options.parent.$store
            }
        }
    }
    let install = function (_Vue) {
        // 判断是不是已经添加过了
        if (Vue) {
            console.error(
                '[vuex] already installed. Vue.use(Vuex) should be called only once.'
            )
            return
        }
        Vue = _Vue
        applyMixin(Vue)
    }

    // auto install in dist mode
    if (typeof window !== 'undefined' && window.Vue) {
        install(window.Vue)
    }



})();

// 这个是认识store的构造函数
; (function () {
    return
    let  installModule = function(store, rootState, path, module, hot) {
        const isRoot = !path.length
        const {
            state,
            actions,
            mutations,
            getters,
            modules
        } = module

        // set state
        if (!isRoot && !hot) {
            const parentState = getNestedState(rootState, path.slice(0, -1))
            const moduleName = path[path.length - 1]
            store._withCommit(() => {
                Vue.set(parentState, moduleName, state || {})
            })
        }

        if (mutations) {
            Object.keys(mutations).forEach(key => {
                registerMutation(store, key, mutations[key], path)
            })
        }

        if (actions) {
            Object.keys(actions).forEach(key => {
                registerAction(store, key, actions[key], path)
            })
        }

        if (getters) {
            wrapGetters(store, getters, path)
        }

        if (modules) {
            Object.keys(modules).forEach(key => {
                installModule(store, rootState, path.concat(key), modules[key], hot)
            })
        }
    }
    class Store {
        constructor(options = {}) {
            // assert(Vue, `must call Vue.use(Vuex) before creating a store instance.`)
            // assert(typeof Promise !== 'undefined', `vuex requires a Promise polyfill in this browser.`)

            const {
                state = {},
                plugins = [],
                strict = false
            } = options

            // store internal state
            this._options = options
            this._committing = false
            this._actions = Object.create(null)
            this._mutations = Object.create(null)
            this._wrappedGetters = Object.create(null)
            this._runtimeModules = Object.create(null)
            this._subscribers = []
            this._watcherVM = new Vue()

            // bind commit and dispatch to self
            const store = this
            const { dispatch, commit } = this
            this.dispatch = function boundDispatch(type, payload) {
                return dispatch.call(store, type, payload)
            }
            this.commit = function boundCommit(type, payload, options) {
                return commit.call(store, type, payload, options)
            }

            // strict mode
            this.strict = strict

            // init root module.
            // this also recursively registers all sub-modules
            // and collects all module getters inside this._wrappedGetters
            installModule(this, state, [], options)

            // initialize the store vm, which is responsible for the reactivity
            // (also registers _wrappedGetters as computed properties)
            resetStoreVM(this, state)

            // apply plugins
            plugins.concat(devtoolPlugin).forEach(plugin => plugin(this))
        }

    }


    
})();

//一个简短版本的store函数
;(function(){
  //return
  import { reactive, inject } from 'vue'

// 定义了一个全局的 key，用于在 Vue 组件中通过 inject API 访问 store 对象
const STORE_KEY = '__store__'

// 用于获取当前组件的 store 对象
let  useStore = function() {
    return inject(STORE_KEY)
}
// 创建一个新的 Store 实例并返回
let createStore =function(options) {
    return new Store(options);
}
// Store 类，用于管理应用程序状态
class Store {

    // 构造函数，接收一个包含 state、mutations、actions 和 getters 函数的对象 options，然后将它们保存到实例属性中
    constructor(options) {
        this.$options = options;

        // 使用 Vue.js 的 reactive API 将 state 数据转换为响应式对象，并保存到实例属性 _state 中        
        this._state = reactive({
            data: options.state()
        })

        // 将 mutations 和 actions 函数保存到实例属性中
        this._mutations = options.mutations
        this._actions = options.actions;

        // 初始化 getters 属性为空对象
        this.getters = {};

        // 遍历所有的 getters 函数，将其封装成 computed 属性并保存到实例属性 getters 中
        Object.keys(options.getters).forEach(name => {
            const fn = options.getters(name);
            this.getters[name] = computed(() => fn(this.state));
        })
    }

    // 用于获取当前状态数据
    get state() {
        return this._state.data
    }
    // 获取mutation内定义的函数并执行
    commit (type, payload) {
        const entry = this._mutations[type]
        entry && entry(this.state, payload)
    }
    // 获取actions内定义的函数并返回函数执行结果
    // 简略版dispatch
    dispatch (type, payload) { 
        const entry = this._actions[type];
        return entry && entry(this, payload)
    }

    // 将当前 store 实例注册到 Vue.js 应用程序中
    install(app) {
        app.provide(STORE_KEY, this)
    }
}



// 导出 createStore 和 useStore 函数，用于在 Vue.js 应用程序中管理状态
let obj = {
    createStore,
    useStore
}
})();